package com.hz.tgb.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * IP地址获取
 *
 * @author hezhao on 2020-02-13 17:57
 */
@Slf4j
public class IpAddrUtil {

    /**
     * 获取用户的IP地址(可以穿透代理)
     *
     * @return ip
     */
    public static String getIpAddr() {
        HttpServletRequest request = getRequest();

        // 不使用request.getRemoteAddr()的原因是有可能用户使用了代理软件方式避免真实IP地址, 可是，如果通过了多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串IP值

        // 优先取x-original-forwarded-for
        String ip = request.getHeader("x-original-forwarded-for");
        log.info("IpAddrUtil ::: x-original-forwarded-for ip: " + ip);
        if (!ipIsNullOrEmpty(ip)) {
            // 多次反向代理后会有多个ip值，第一个ip才是真实ip
            if (ip.contains(",")) {
                ip = ip.split(",")[0];
            }
        }

        if (ipIsNullOrEmpty(ip)) {
            ip = request.getHeader("x-forwarded-for");
            log.info("IpAddrUtil ::: x-forwarded-for ip: " + ip);
            if (!ipIsNullOrEmpty(ip)) {
                // 多次反向代理后会有多个ip值，第一个ip才是真实ip
                if (ip.contains(",")) {
                    ip = ip.split(",")[0];
                }
            }
        }
        if (ipIsNullOrEmpty(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
            log.info("IpAddrUtil ::: Proxy-Client-IP ip: " + ip);
        }
        if (ipIsNullOrEmpty(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
            log.info("IpAddrUtil ::: WL-Proxy-Client-IP ip: " + ip);
        }
        if (ipIsNullOrEmpty(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
            log.info("IpAddrUtil ::: HTTP_CLIENT_IP ip: " + ip);
        }
        if (ipIsNullOrEmpty(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            log.info("IpAddrUtil ::: HTTP_X_FORWARDED_FOR ip: " + ip);
        }
        if (ipIsNullOrEmpty(ip)) {
            ip = request.getHeader("X-Real-IP");
            log.info("IpAddrUtil ::: X-Real-IP ip: " + ip);
        }
        if (ipIsNullOrEmpty(ip)) {
            ip = request.getRemoteAddr();
            log.info("IpAddrUtil ::: getRemoteAddr ip: " + ip);
        }
        log.info("IpAddrUtil ::: 获取客户端ip: " + ip);
        return ip;
    }

    private static boolean ipIsNullOrEmpty(String ip) {
        return ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip);
    }

    public static HttpServletRequest getRequest() {
        return getServletRequestAttributes().getRequest();
    }

    private static ServletRequestAttributes getServletRequestAttributes() {
        return (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    }

}
